package org.firefly.fx.service.common.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.firefly.fx.constants.ConfigInfo;
import org.firefly.fx.service.common.IWebsocketSessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Service
public class WebSocketSessionServiceImpl implements IWebsocketSessionService{
	private static final Logger log = LoggerFactory.getLogger(WebSocketSessionServiceImpl.class);

	private static Map<String,WebSocketSession> sessionMap = new  HashMap<String,WebSocketSession>();
	
	@Override
	public void saveSession(String userId, WebSocketSession session) {
		this.sessionMap.put(userId, session);
	}

	@Override
	public void removeSession(String userId) {
		this.sessionMap.remove(userId);
	}

	@Override
	public void removeSession(WebSocketSession session) {
		Map<String,Object> atts = session.getAttributes();
		String userId = (String) atts.get(ConfigInfo.USER_ID);
		this.removeSession(userId);
	}

	@Override
	public boolean sendMsgToUser(long userId, String msg) {
		return this.sendMsgToUser(String.valueOf(userId), msg);
	}

	@Override
	public boolean sendMsgToUser(String userId, String msg) {
		WebSocketSession session = this.sessionMap.get(userId);
		return this.sendmsg(session, msg);
	}

	private boolean sendmsg(WebSocketSession session,String msg){
		if(session==null){
			return false;
		}
		
		TextMessage text = new TextMessage(msg);
		
		try {
			if(session.isOpen()){
				session.sendMessage(text);
			}
		} catch (IOException e) {
			e.printStackTrace();
			log.error("send msg error!", e);
			return false;
		}
		
		return true;
	}
	
	@Override
	public boolean sendMsgToUsers(String msg) {
		Collection<WebSocketSession> c = sessionMap.values();
		if(c==null || c.size()==0){
			log.debug("sessionMap 为空！");
			return false;
		}
		
		Iterator<WebSocketSession> it = c.iterator();
		while(it.hasNext()){
			this.sendmsg(it.next(), msg);
		}
		
		return true;
	}

	@Override
	public int onlineUsersCount() {
		return this.sessionMap.size();
	}

	@Override
	public List<Long> onlineUsers() {
		Set<String> keySet = this.sessionMap.keySet();
		List<Long> userIdList = new ArrayList<Long>();
		for(String id:keySet){
			userIdList.add(Long.parseLong(id));
		}
		
		return userIdList;
	}

	@Override
	public boolean isOnline(long userId) {
		return (this.sessionMap.get(String.valueOf(userId))!=null);
	}
	
	@Override
	public boolean isOnline(String userId) {
		WebSocketSession wss = this.sessionMap.get(userId);
		if(wss==null){
			return false;
		}
		return true;
	}
}
